<?php
/**
 *
 * @author  Devret
 * @mail    461313128@qq.com
 * @create  2020-02-18 16:54
 * https://sixcloud.co/
 * https://gitee.com/devret/AuthorizationSystem.git
 */

define('ROOT_PATH', rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/'));
include(ROOT_PATH . "/api.inc.php");

class AddSqService
{
    /**
     * 查找卡密
     * @param $km 卡密字符串
     * @return mixed 返回卡密信息
     */
    private function findKmByKm($km)
    {
        $sql = "SELECT * FROM `sixcloud_kms` where  card = ?";

        $rows = SQL::Read($sql, array($km));
        if (count($rows) <= 0) {
            die(OperateResult::out(false, "卡密不存在", ""));
        }
        if ($rows[0]['use'] == 1) {
            die(OperateResult::out(false, "卡密已被使用！", $rows[0]['usedate']));
        }
        return $rows[0];
    }


    /**
     * 检测帐号是否存在授权
     * @param $auth 授权帐号
     */
    private function findSqByAuth($auth)
    {
        $sql = "SELECT * FROM  `sixcloud_infos` where auth=?";
        $rows = SQL::Read($sql, array($auth));
        $rowsLength = count($rows);
        if ($rowsLength > 0 && $rows[0]['expiredate'] == 1) {
            die(OperateResult::out(false, "此帐号已有永久授权", $rows[0]));
        }


        if ($rowsLength > 0) {
            //存在期限授权
            return OperateResult::outArray(true, "存在期限授权", $rows[0]);
        } else {
            //授权不存在
            return OperateResult::outArray(false, "授权不存在", null);
        }
    }

    public function addSqByKm($authorizer, $auth, $km)
    {
        //检测帐号是否存在授权-有则返回授权信息,没有则返回false
        $ret = self::findSqByAuth($auth);
        //检测卡密状态
        $retKmArray = self::findKmByKm($km);

        //更新卡密-此处应该使用事物（待优化）
        $sql = "UPDATE `sixcloud_kms` SET `use` = ?, `usedate` =? WHERE `card` = ?";
        $data = array(1, NOW_DATE, $km);
        $isSuccess = SQL::Write($sql, $data);
        if ($isSuccess == false) {
            return OperateResult::out($isSuccess, $isSuccess ? "卡密授权失败！" : "卡密授权失败", null);
        }
        $now = NOW_DATE;
        $time = date('Y-m-d h:m:s', strtotime("{$now} +" . $retKmArray['expiredate'] . " day"));

        if ($ret['success'] == false) {
            //帐号没有授权
            //插入授权-此处应该使用事物（待优化）
            $sql = "INSERT INTO `sixcloud_infos`(`authkm`, `authorizer`, `auth`, `key`, `expiredate`, `createdate`, `status`, `remark`) VALUES (?, ?, ?, ?, ?,?, ?,?)";
            if ($retKmArray['expiredate'] != 0) {
                $time = date('Y-m-d h:m:s', strtotime("{$now} +" . $retKmArray['expiredate'] . " day"));
            } else {
                $time = 1;
            }
            $data = array(
                $km,
                $authorizer,
                $auth,
                Utils::randomkeys(16),
                $time,
                $now,
                1,
                "来源于卡密授权"
            );
            $isSuccess = SQL::Write($sql, $data);
            return OperateResult::out($isSuccess, $isSuccess ? "帐号授权成功！" : "帐号授权失败", null);
        } else {
            //帐号存在期限授权
            $sql = "UPDATE `sixcloud_infos` SET  `authkm`=?, `expiredate` = ? WHERE  `auth` = ?";
            if ($retKmArray['expiredate'] != 0) {
                $time = date('Y-m-d h:m:s', strtotime("{$ret['data']['expiredate']} +" . $retKmArray['expiredate'] . " day"));
            } else {
                $time = 1;
            }
            $data = array($km, $time, $auth);
            $isSuccess = SQL::Write($sql, $data);
            return OperateResult::out($isSuccess, $isSuccess ? "帐号续期授权成功！" : "帐号续期授权失败", null);
        }
    }


    //用户检测授权-web端
    public function queryByAuth($auth)
    {
        $sql = "SELECT * FROM  `sixcloud_infos` where auth=?";
        $rows = SQL::Read($sql, array($auth));
        if (count($rows) <= 0) {
            die(OperateResult::out(false, "未授权", ""));
        }
        die(OperateResult::out(true, "已授权", $rows[0]));
    }
}